﻿using HtmlAgilityPack;
using Model.CustomApp;
using OpenInterface;
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Linq;
using IRepository;

namespace OpenImplement
{
    public class AnalyzerStandardcn : IAnalyzer
    {
        private IDefaultRepository<StandardcnDetailModel> defaultRepository = null;
        public AnalyzerStandardcn()
        {
            defaultRepository = Service.ServiceManager.GetService<IDefaultRepository<StandardcnDetailModel>>();
        }
        public void Analyze(string url, string html, Action<string, HandlerType> actHandlerUrl)
        {
            if (url.EndsWith("search_stand.asp"))
            {
                var doc = new HtmlDocument();
                doc.LoadHtml(html);
                var root = doc.DocumentNode;
                var links = root.Descendants("a").Where(a => a.OuterHtml.Contains("search_stand.asp?Hy_Type"));
                foreach (var link in links)
                {
                    if (link.InnerText.Trim().Equals("国家标准(GB)")) continue;
                    var href = link.GetAttributeValue("href", "#");
                    href = string.Format("http://www.standardcn.com/standard_plan/{0}={1}&page=1", href.Split('=')[0],System.Web.HttpUtility.UrlEncode(href.Split('=')[1],Encoding.GetEncoding("gb2312")));
                    actHandlerUrl.Invoke(href, HandlerType.Default);
                }
            }
            ///解析列表页
            else if (url.Contains("search_stand") && url.Contains("page="))
            {

                //if (url.EndsWith("&page=1"))
                //{
                //    //预先抓取所有列表页
                //    var regex = new Regex(@"检索到符合条件的数据<span class=""style7"">(?<count>\d+)</span>条数据", RegexOptions.IgnoreCase);

                //    if (regex.IsMatch(html))
                //    {
                //        var count = int.Parse(regex.Match(html).Groups["count"].Value);
                //        for (int i = 0; i < count / 25; i++)
                //        {
                //            var listPage = "http://www.standardcn.com/standard_plan/search_stand.asp?HY_Type=%C7%E1%B9%A4&page=" + (2 + i);
                //            //TODO handler url
                //            actHandlerUrl.Invoke(listPage, -1);
                //        }
                //    }
                //}
                ///解析详情页地址
                var doc = new HtmlDocument();
                doc.LoadHtml(html);
                var root = doc.DocumentNode;
                var trs = root.Descendants("a").Where(tr => tr.OuterHtml.Contains("list_standard_content"));
                foreach (var tr in trs)
                {
                    try
                    {
                        //var td = tr.Descendants("td").Where(d => d.InnerHtml.Contains("list_standard_content")).FirstOrDefault();

                        //var a = td.Descendants("a").FirstOrDefault();
                        var a = tr;
                        var href = a.GetAttributeValue("href", "#");
                        if (href.StartsWith("list_standard_content"))
                        {
                            href = "http://www.standardcn.com/standard_plan/" + href;
                            //TODO handler url
                            actHandlerUrl.Invoke(href, HandlerType.ReSetDepth);
                        }
                    }
                    catch (Exception)
                    {
                        ;
                    }
                }

                var urlInfo = url.Split(new String[] { "page=" }, StringSplitOptions.None);
                //往下翻页
                var newIndex = int.Parse(urlInfo[1]) + 1;


                //获取总页数
                var regex = new Regex(@"检索到符合条件的数据<span class=""style7"">(?<count>\d+)</span>条数据", RegexOptions.IgnoreCase);

                if (regex.IsMatch(html))
                {
                    var count = int.Parse(regex.Match(html).Groups["count"].Value);
                    if (newIndex < count / 25 + 1)
                        actHandlerUrl.Invoke(string.Format("{0}page={1}", urlInfo[0], newIndex), HandlerType.ReSetDepth);
                }



            }
            //解析详情页
            else if (url.Contains("list_standard_content"))
            {
                var doc = new HtmlDocument();
                doc.LoadHtml(html);
                var root = doc.DocumentNode;
                var table = root.Descendants("table").Where(d => d.InnerText.Contains("标准编号") && d.InnerText.Contains("内容介绍")).FirstOrDefault();
                table = table.Descendants("table").Where(d => d.InnerText.Contains("标准编号") && d.InnerText.Contains("内容介绍")).FirstOrDefault();
                table = table.Descendants("table").Where(d => d.InnerText.Contains("标准编号") && d.InnerText.Contains("内容介绍")).FirstOrDefault();
                var trs = table.Descendants("tr");
                var builder = new List<string>();
                var stdInfo = new StandardcnDetailModel { Url = url };
                foreach (var tr in trs)
                {

                    var tds = tr.Descendants("td").ToList();
                    var dt = tds[0].InnerText.Replace(" ", "").Replace("\n", "");
                    var dd = tds[1].InnerText.Replace("&nbsp;", "");

                    builder.Add(string.Format("{0}={1}", dt, dd));

                    if (dt.Contains("标准编号"))
                        stdInfo.StdNo = dd;
                    else if (dt.Contains("标准名称"))
                        stdInfo.StdName = dd;
                    else if (dt.Contains("英文名称"))
                        stdInfo.ENStdName = dd;
                    else if (dt.Contains("代替号"))
                        stdInfo.ReplaceStdNo = dd;
                    else if (dt.Contains("采用标准"))
                        stdInfo.PubDate = dd;
                    else if (dt.Contains("归口单位"))
                        stdInfo.GKUnit = dd;
                    else if (dt.Contains("起草单位"))
                        stdInfo.QCUnit = dd;
                    else if (dt.Contains("分类号"))
                        stdInfo.CHStdCls = dd;
                    else if (dt.Contains("国际分类号"))
                        stdInfo.NaStdCls = dd;
                    else if (dt.Contains("发布日期"))
                        stdInfo.PubDate = dd;
                    else if (dt.Contains("实施日期"))
                        stdInfo.ImpDate = dd;
                    else if (dt.Contains("内容介绍"))
                        stdInfo.Introduction = dd;

                }
                stdInfo.BaseInfo = string.Join(";", builder);


                //TODO save
                defaultRepository.Add(stdInfo, Common.Constant.AppSetting.DefaultDataConstr);
            }
        }
    }
}
